package com.grf.config;

import com.grf.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;

/**
 *
 */
public class UserRealm extends AuthorizingRealm {

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        //拿到当前登录的用户对象
        User currentUser = (User)subject.getPrincipal();
        //设置当前用户权限，其实是数据库读出来的
        for (String perm : currentUser.getPerms()) {
            info.addStringPermission(perm);
        }

        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");

        //模拟数据库数据
        User user = new User();
        user.setUserName("grf");
        user.setPassword("1");
        //权限数组
        ArrayList<String> perms = new ArrayList<>();
        perms.add("user:add");
        perms.add("user:update");
        user.setPerms(perms);
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        if (!userToken.getUsername().equals(user.getUserName())) {
            return null; //抛出异常
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }

}
